﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using SilverlightApplication.LanguageResources;
using SilverlightApplication.UIControls;
using SilverlightApplication.UIControls.Carousel;


namespace SilverlightApplication
{
    public partial class SearchPanels : UserControl
    {
        private Boolean basicActive;
        private Boolean advActive;
        private WaitingForResults.WaitingForResults wfr;
        private Carousel carousel;
        private ItemPanel itemPanel;
        private SearchController searchController;
        private int animationsPlaying;

        protected ISearchPanelContent basicPanelBook;
        protected ISearchPanelContent advancedPanelBook;

        protected ISearchPanelContent basicPanelDVD;
        protected ISearchPanelContent advancedPanelDVD;

        protected ISearchPanelContent basicPanel;
        protected ISearchPanelContent advancedPanel;

        private SearchType? panelSearchType = null;
        private bool contentPanelsNeedChanging = false;
        private PanelType? previouslyOpened;

        public SearchController SearchController
        {
            set {
                searchController = value;
                searchController.firstPageArrivedEventHandler += new SearchController.FirstPageArrivedEventHandler(value_resultsArrived);
            }
            get {
                return searchController;
            }
        }

        public SearchPanels(WaitingForResults.WaitingForResults wfr)
        {
            InitializeComponent();

            initData();
            this.wfr = wfr;
            tbkSearch.Text = LanguageLoader.GetString("tbkSearch");
            tbkClear.Text = LanguageLoader.GetString("tbkClear");
            tbxBasicSearch.Text = LanguageLoader.GetString("tbxBasicSearch");
            txbAdvanced.Text = LanguageLoader.GetString("txbAdvanced");
            NoInputMsg.Text = LanguageLoader.GetString("NoInputMsg");
            cnvPopupMessage.Visibility = Visibility.Collapsed;

            animationsPlaying = 0;

            basicPanelBook = new BookBasicPanel(this);
            advancedPanelBook = new BookAdvancedPanel(this);

            basicPanelDVD = new DVDBasicPanel(this);
            advancedPanelDVD = new DVDAdvancedPanel(this);
        }

        public SearchType PanelSearchType
        {
            get { 
                return (SearchType)panelSearchType;
            }
            set {
                if (animationsPlaying == 0 && panelSearchType != value)
                {
                    if (basicActive)
                    {
                        BasicPanelClicked();
                        contentPanelsNeedChanging = true;
                        previouslyOpened = PanelType.Basic;
                    }
                    else if (advActive)
                    {
                        AdvancedPanelClicked();
                        contentPanelsNeedChanging = true;
                        previouslyOpened = PanelType.Advanced;
                    }
                    else
                    {
                        BasicPanelClicked();
                        SetSearchType(value);
                        contentPanelsNeedChanging = false;
                        previouslyOpened = null;
                    }
                    ClearPanels();
                    panelSearchType = value;
                }
            }
        }

        void SetSearchType(SearchType searchType)
        {
            if (searchType == SearchType.Book)
            {
                grdBasicContent.Children.Remove((UserControl)basicPanelDVD);
                grdAdvancedContent.Children.Remove((UserControl)advancedPanelDVD);

                grdBasicContent.Children.Add((UserControl)basicPanelBook);
                grdAdvancedContent.Children.Add((UserControl)advancedPanelBook);

                basicPanel = basicPanelBook;
                advancedPanel = advancedPanelBook;
            }
            else // searchType == SearchType.DVD
            {
                grdBasicContent.Children.Remove((UserControl)basicPanelBook);
                grdAdvancedContent.Children.Remove((UserControl)advancedPanelBook);

                grdBasicContent.Children.Add((UserControl)basicPanelDVD);
                grdAdvancedContent.Children.Add((UserControl)advancedPanelDVD);

                basicPanel = basicPanelDVD;
                advancedPanel = advancedPanelDVD;
            }

            ConfigurePanels();
        }

        void ConfigurePanels()
        {
            UserControl basicUserControl = grdBasicContent.Children[0] as UserControl;
            Grid basicPanelContent = (Grid) basicUserControl.FindName("LayoutRoot");

            trtBasicPanel.X = basicPanelContent.Width - tbxBasicSearch.ActualWidth + 42;
            trtBasicPanel.Y = basicPanelContent.Height + 104;

            double basicXOffset = 260;
            double basicYOffset = 44;

            DABasicPanelShowX.To = -basicPanelContent.Width + basicXOffset;
            DABasicPanelShowY.To = basicYOffset;

            DABasicPanelHideX.To = trtBasicPanel.X;
            DABasicPanelHideY.To = trtBasicPanel.Y;

            UserControl advancedUserControl = grdAdvancedContent.Children[0] as UserControl;
            Grid advancedPanelContent = (Grid)advancedUserControl.FindName("LayoutRoot");

            trtAdvancedPanel.X = advancedPanelContent.Width - txbAdvanced.ActualWidth + trtBasicPanel.X - 252;
            trtAdvancedPanel.Y = advancedPanelContent.Height + 104;

            DAAdvancedPanelLeftX.To = trtAdvancedPanel.X - trtBasicPanel.X + DABasicPanelShowX.To;
            DAAdvancedPanelRightX.To = trtAdvancedPanel.X;

            double advancedXOffset = 538;
            double advancedYOffset = 44;

            DAAdvancedPanelShowX.To = -advancedPanelContent.Width + advancedXOffset;
            DAAdvancedPanelShowY.To = advancedYOffset;

            DAAdvancedPanelHideX.To = trtAdvancedPanel.X;
            DAAdvancedPanelHideY.To = trtAdvancedPanel.Y;
            DAAdvancedPanelDownY.To = trtAdvancedPanel.Y;

            DAAdvancedPanelHideLeftX.To = DAAdvancedPanelLeftX.To;
            DAAdvancedPanelHideLeftY.To = trtAdvancedPanel.Y;

            double buttonsOffset = 210;

            DAButtonsShowAdvX.To = -advancedPanelContent.Width + buttonsOffset;
            DAButtonsShowBasX.To = -basicPanelContent.Width + buttonsOffset;
        }

        private void initData()
        {
            this.basicActive = false;
            this.advActive = false;
        }

        private void cnvBooksAdvPanel_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            AdvancedPanelClicked();
        }

        public void AdvancedPanelClicked()
        {
            if (animationsPlaying == 0)
            {
                if (this.advActive)
                {
                    carousel.UnFreeze();
                    this.advActive = false;
                    stbAdvancedPanelHide.Begin();
                    stbButtonsHide.Begin();
                    animationsPlaying += 2;
                }
                else
                {
                    carousel.Freeze();
                    this.advActive = true;
                    stbAdvancedPanelShow.Begin();

                    if (this.basicActive)
                    {
                        this.basicActive = false;
                        stbBasicPanelHide.Begin();
                        animationsPlaying++;
                    }

                    stbButtonsShowAdv.Begin();
                    animationsPlaying += 2;
                }
            }
        }

        public void BasicPanelClicked()
        {
            if (animationsPlaying == 0)
            {
                if (this.basicActive)
                {
                    this.hideBasicPanel();
                }
                else
                {
                    this.showBasicPanel();
                }
            }
        }

        public void showBasicPanel()
        {
            if (carousel != null)
            {
                carousel.Freeze();
            }
            this.basicActive = true;
            stbBasicPanelShow.Begin();

            if (this.advActive)
            {
                this.advActive = false;
                stbAdvancedPanelHideLeft.Begin();
            }
            else
            {
                stbAdvancedPanelLeft.Begin();
            }
            stbButtonsShowBas.Begin();
            animationsPlaying += 3;
        }

        public void hideBasicPanel()
        {
            carousel.UnFreeze();
            this.basicActive = false;
            stbBasicPanelHide.Begin();
            stbButtonsHide.Begin();
            stbAdvancedPanelRight.Begin();
            animationsPlaying += 3;
        }

        private void cnvBooksBasicPanel_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            BasicPanelClicked();
        }

        public void setCarousel(Carousel carousel)
        {
            this.carousel = carousel;
        }

        public void setItemPanel(ItemPanel itemPanel)
        {
            this.itemPanel = itemPanel;
        }

        private void cnvSearchButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            cnvSearchUp.Visibility = Visibility.Collapsed;
            cnvSearchDown.Visibility = Visibility.Visible;
        }

        private void cnvSearchButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            this.beginSearch();
        }

        public void beginSearch()
        {
            SearchCriteria criteria = null;

            if (!StatusBar.statusBar.Equals("Ready"))
            {
                NoInputMsg.Text = LanguageLoader.GetString("NoKeyMsg");
                cnvPopupMessage.Visibility = Visibility.Visible;
                stbMessage.Begin();
            }
            else
            {
                NoInputMsg.Text = LanguageLoader.GetString("NoInputMsg"); 
                // Search Start
                if (this.basicActive)
                {
                    if (basicPanel.FieldsValidate())
                    {
                        criteria = basicPanel.GetSearchCriteria();
                    }
                    else
                    {
                        cnvPopupMessage.Visibility = Visibility.Visible;
                        stbMessage.Begin();
                    }
                }
                else // this.advActive
                {
                    if (advancedPanel.FieldsValidate())
                    {
                        criteria = advancedPanel.GetSearchCriteria();
                    }
                    else
                    {
                        cnvPopupMessage.Visibility = Visibility.Visible;
                        stbMessage.Begin();
                    }
                }

                // If the fields validated, we Do the Search
                if (criteria != null)
                {
                    this.SearchController.DoSearch(criteria);

                    if (this.basicActive)
                    {
                        BasicPanelClicked();
                    }
                    else if (this.advActive)
                    {
                        AdvancedPanelClicked();
                    }

                    DisableSearchButton();
                    ShowCentralLogo(false);

                    this.wfr.Visibility = Visibility.Visible;
                    this.wfr.stbWaitAnim.Begin();

                    itemPanel.HidePanel();
                }
            }
        }

        private void DisableSearchButton()
        {
            cnvSearchButton.MouseLeftButtonUp -= new MouseButtonEventHandler(cnvSearchButton_MouseLeftButtonUp);
            cnvSearchButton.MouseLeftButtonDown -= new MouseButtonEventHandler(cnvSearchButton_MouseLeftButtonDown);
            ((TextBlock)((Grid)cnvSearchButton.FindName("cnvSearchUp")).FindName("tbkSearch")).Foreground = new SolidColorBrush(Colors.Gray);
        }

        private void EnableSearchButton()
        {
            cnvSearchButton.MouseLeftButtonUp += new MouseButtonEventHandler(cnvSearchButton_MouseLeftButtonUp);
            cnvSearchButton.MouseLeftButtonDown += new MouseButtonEventHandler(cnvSearchButton_MouseLeftButtonDown);
            ((TextBlock)((Grid)cnvSearchButton.FindName("cnvSearchUp")).FindName("tbkSearch")).Foreground = (LinearGradientBrush)Resources["bshBlue"];
        }

        void value_resultsArrived()
        {
            this.wfr.stbWaitAnim.Stop();
            this.wfr.Visibility = Visibility.Collapsed;

            EnableSearchButton();

            if (this.basicActive)
            {
                BasicPanelClicked();
            }
            else if (this.advActive)
            {
                AdvancedPanelClicked();
            }
        }

        private void cnvClearButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            cnvClearUp.Visibility = Visibility.Collapsed;
            cnvClearDown.Visibility = Visibility.Visible;
        }

        private void cnvClearButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            cnvClearUp.Visibility = Visibility.Visible;
            cnvClearDown.Visibility = Visibility.Collapsed;

            if (this.basicActive)
            {
                basicPanel.ClearFields();
            }
            else
            {
                advancedPanel.ClearFields();
            }
        }

        private void stbMessage_Completed(object sender, EventArgs e)
        {
            cnvPopupMessage.Visibility = Visibility.Collapsed;
        }

        private void AnimationCompleted(object sender, EventArgs e)
        {
            lock (typeof(int))
            {
                animationsPlaying--;
            }

            if (animationsPlaying == 0 && contentPanelsNeedChanging)
            {
                SetSearchType((SearchType)panelSearchType);
                contentPanelsNeedChanging = false;

                if (previouslyOpened == PanelType.Basic)
                    BasicPanelClicked();
                else if (previouslyOpened == PanelType.Advanced)
                    AdvancedPanelClicked();
            }

            if (animationsPlaying == 0 && !(basicActive || advActive))
            {
                
            }
        }

        private void ShowCentralLogo(bool showLogo)
        {
            if (showLogo)
            {
                searchController.MagnifierCtrl.Play();
                searchController.MagnifierCtrl.Visibility = Visibility.Visible;
            }
            else
            {
                searchController.MagnifierCtrl.Stop();
                searchController.MagnifierCtrl.Visibility = Visibility.Collapsed;
            }
        }

        public void ClearSearchResults()
        {
            searchController.ClearSearch();
            ShowCentralLogo(true);
        }

        private void ClearPanels()
        {
            if (basicPanel != null)
            {
                basicPanel.ClearFields();
            }
            if (advancedPanel != null)
            {
                advancedPanel.ClearFields();
            }
        }
    }

    public enum SearchType
    {
        Book,
        DVD
    }

    public enum PanelType
    {
        Basic,
        Advanced
    }
}
